package day23;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Iterator;

public class ChatServer {
	private static HashSet<PrintWriter> pws = new HashSet<PrintWriter>();

	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(10222);
		while (true) {
			Socket s = ss.accept();
			Thread t = new MessageProcessor(s);
			t.start();
		}
	}

	private static class MessageProcessor extends Thread {
		private Socket s;

		public MessageProcessor(Socket s) {
			this.s = s;
		}

		public void run() {
			try {
				InputStream is = s.getInputStream();
				OutputStream os = s.getOutputStream();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				PrintWriter pw = new PrintWriter(os);
				pws.add(pw);
				while (true) {
					String str = br.readLine();
					tellEveryOne(str);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		private void tellEveryOne(String msg) {
			for (Iterator<PrintWriter> it = pws.iterator(); it.hasNext();) {
				PrintWriter pw = it.next();
				pw.println(msg);
				pw.flush();
			}
		}
	}
}
